package cn.schtwz.baselib.base.quickCode

import androidx.lifecycle.MutableLiveData
import cn.schtwz.baselib.base.BaseBean
import cn.schtwz.baselib.base.BaseViewModel
import cn.schtwz.baselib.loading.CommonLoadingState


abstract class BaseListViewModel<B : BaseBean>(val repository: BaseListRepository<B>) : BaseViewModel() {

    companion object {
        const val limit = 10

    }

    val datas: MutableLiveData<List<B>> by lazy { MutableLiveData<List<B>>() }
    val refreshing: MutableLiveData<Boolean> = MutableLiveData(false) //是否刷新
    val page: MutableLiveData<Int> = MutableLiveData(1) //分页
    val loadingState: MutableLiveData<CommonLoadingState> = MutableLiveData(CommonLoadingState.IDLE)

    open fun loadDatas(parameter: HashMap<String, Any>) = launchUI {
        page.value = (page.value?.plus(1))
        parameter.put("page", page.value!!)
        parameter.put("limit", limit)
        val result = repository.getDatas(parameter)
        datas.value = result.data
    }


    open fun onRefresh(parameter: HashMap<String, Any>) = launchUI({
        loadingState.postValue(CommonLoadingState.LOADING)
        page.value = (1)
        parameter.put("page", page.value!!)
        parameter.put("limit", limit)
        val result = repository.getDatas(parameter)
        datas.value = result.data
        refreshing.postValue(false)
        if (result.data.isEmpty()) {
            loadingState.postValue(CommonLoadingState.EMPTY)
        } else {
            loadingState.postValue(CommonLoadingState.IDLE)
        }
    }, {
        refreshing.postValue(false)
        loadingState.postValue(CommonLoadingState.ERROR)
    })


}